package com.ksl.kinglockguard.receiver;


import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ksl.kinglockguard.LockApplication;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.network.ConnectChangeListener;
import com.ksl.kinglockguard.network.ConnectChangeListener.ConnectChangeListenerInterface;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.network.appupdate.UpdateAppTaskListener;
import com.ksl.kinglockguard.pay.upload.OrderUpload;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;

public class ConnectionChangeReceiver extends BroadcastReceiver{

	private ConnectivityManager connectivityManager;
	private Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null) {
				// 3G网络
				ArrayList<ConnectChangeListenerInterface> listeners = ConnectChangeListener.getInstance().getListeners();
				if(listeners!=null){
					for (int i = 0; i <listeners.size(); i++) {
						listeners.get(i).onConnectChange();
					}
				}
			if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				MyLog.i("jyh1", "~~~3G网络 onConnectChange~~~~~");
				NetworkTask.count = 0;
				uploadPayData();
			}
		}
		
		//
		NetworkInfo wifiNetworkInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo.isConnected()) { // wifi连接的情况下,检查数据上传和版本更新
			long lastUpdateTime = SharePreferenceSdkData.getLastCheckUpdateTime(context);
			boolean timeInterval = System.currentTimeMillis()-lastUpdateTime > LockApplication.TIME_INTERVAL_ONE_WEEK;
			UpdateAppTaskListener listener = new UpdateAppTaskListener(context,UpdateAppTaskListener.NOTIFY_TYPE_NOTIFICATION,null);
			
			if(lastUpdateTime == 0){
				SharePreferenceSdkData.setLastCheckUpdateTime(context, System.currentTimeMillis());
			}
			if(lastUpdateTime != 0 && timeInterval){
				//注意:  检查更新不能放在子线程中
				NetConnectTask updateAppTask = NetworkTask.requestUpdateMyApp(context);
				updateAppTask.setListener(listener);
			}
			MyLog.i("jyh1", "~~~wifi连接 onConnectChange~~~~~");
			NetworkTask.count = 0;
			uploadPayData();
		}
	}
	private void uploadPayData(){
		OrderUpload.getInstance().uploadWhenNetAvailable(context);
	}
	
}

